package com.mjk.manager.usercenter.sclogin;

import cn.dev33.satoken.stp.StpUtil;
import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.base.work.BaseWork;
import com.mjk.common.base.work.annotation.BeeApi;
import com.mjk.common.base.work.annotation.BeeWork;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeComplexQueryWrapper;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;

import com.mjk.common.core.redis.datatype.RedisUtils;
import com.mjk.common.tools.encrypt.MD5Util;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.util.MapUtils;
import com.mjk.common.util.SnowFlake;
import com.mjk.common.util.TreeUtils;
import com.mjk.manager.amis.constans.Constants;
import com.mjk.manager.amis.core.model.PlatUser;
import com.mjk.manager.amis.core.model.SysMenu;
import com.mjk.manager.amis.core.model.SysRoleMenu;
import com.mjk.manager.usercenter.sclogin.dto.LogDto;
import com.mjk.manager.usercenter.sclogin.event.LoginEvent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户登入模块
 * @author Administrator
 *
 */
@BeeWork(work = "sclogin", isDynamic = true)
public class ScLoginWork extends BaseWork {
	@Autowired
	private BeeDBService beeDBService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ApplicationEventPublisher publisher;
	public BeeResponse login(LogDto dto) {
		needParams(dto, LogDto::getUserName,LogDto::getPassWord);
		BeeQueryWrapper wrapper = new BeeQueryWrapper(new PlatUser());
		wrapper.eq(PlatUser::getLOGIN_NAME,dto.getUserName());
		PlatUser user = (PlatUser) beeDBService.findOneByWrapper(wrapper);
		String captchaCode = (String) RedisUtils.get(redisTemplate, Constants.CAPTCHA_CODE);
		Long captchaTimeout = (Long) RedisUtils.get(redisTemplate,Constants.CAPTCHA_TIMEOUT);
		if (StringUtils.isBlank(captchaCode) || captchaTimeout == null || captchaTimeout < System.currentTimeMillis()
				|| !captchaCode.equalsIgnoreCase(dto.getCaptcha())) {
			return BeeError.LOGIN_ERROR_CHECKCODE_ERROR.tranceError();
		}
		if(ObjectUtils.isEmpty(user)) {
			//用户名不存在
			return BeeError.LOGIN_ERROR_ACCOUNT_NOT_EXIT.tranceError();
		}
		if(ObjectUtils.isEmpty(user.getPASSWORD())){
			return BeeError.LOGIN_ERROR_PWD_NOT_EXIT.tranceError();
		}
		String pwd = MD5Util.lowMd5(user.getLOGIN_NAME()+dto.getPassWord()+user.getSALT());
		if(!user.getPASSWORD().equalsIgnoreCase(pwd)){
			BizLogger.info("model pwd:"+dto.getPassWord()+"---user pwd"+MD5Util.lowMd5(user.getPASSWORD()));
			return BeeError.LOGIN_ERROR_PWD_ERROR.tranceError();
		}
		user.setPASSWORD("");
		Map<String,Object> result = new HashMap<>();
		result.put("token", SnowFlake.getUid());
		result.put("curUser", user);
        //通知需要单JVM 不需要在集群环境推送
        publisher.publishEvent(new LoginEvent(user.getId() + "", user.getLOGIN_NAME(), MapUtils.getString(result, "token")));
		StpUtil.login(dto.getUserName());
		result.put(StpUtil.getTokenName(), StpUtil.getTokenInfo());
		List<SysMenu> menus;
		//登入用户的菜单信息
		if("admin".equals(user.getLOGIN_NAME())){
			BeeQueryWrapper wrapper1 = new BeeQueryWrapper(SysMenu.class);
			wrapper1.eq(SysMenu::getDELETED,false);
			wrapper1.orderBy(" seq ");
			menus = beeDBService.findManyByWrapper(wrapper1);
		}else{
			BeeComplexQueryWrapper wrapper1 = new BeeComplexQueryWrapper(SysMenu.class,"a");
			wrapper1.innerJoin(SysRoleMenu.class,"b").on(SysMenu::getId,SysRoleMenu::getMENU_ID);
			if(com.mjk.common.util.ObjectUtils.isNotEmpty(user.getRoleIds())) {
				wrapper1.in(SysRoleMenu::getROLE_ID, Arrays.asList(user.getRoles().split(",")));
			}
			wrapper1.eq(SysRoleMenu::getDELETED,false);
			wrapper1.orderBy(" a.seq ");
			menus = beeDBService.findManyByComplexWrapper(wrapper1);
		}
		List<SysMenu> menuTree = TreeUtils.list2Tree(menus, "0", "id", "PID", "children", false);
		result.put("curMenus",menuTree);
		return BeeError.BEE_SUC.tranceError(result);
	}

	public BeeResponse loginOut(LogDto dto){
		StpUtil.logout();
		RedisUtils.remove(redisTemplate,Constants.CAPTCHA_CODE);
		RedisUtils.remove(redisTemplate,Constants.CAPTCHA_TIMEOUT);
		return BeeError.BEE_SUC.tranceError();
	}
	/**
	 * 获取用户菜单列表信息
     */
	@BeeApi(role = "user:add")
	@SuppressWarnings("unchecked")
	public BeeResponse getUserMenus(LogDto dto) {
		BeeQueryWrapper wrapper = new BeeQueryWrapper(new SysMenu());
		wrapper.eq(SysMenu::getDELETED,DEFAULT_DEL_FLAG);
		Map<String,Object> result = new HashMap<>();
        List<SysMenu> menus = beeDBService.findManyByWrapper(wrapper);

        result.put("menu", getTreeList(menus, "0", "apipostMenuId", "parentId", "children", false));
		result.put("permissions", Arrays.asList("list.add","list.edit","list.delete"));
        result.put("dashboardGrid", Arrays.asList("welcome", "about", "time"));
		return BeeError.BEE_SUC.tranceError(result);
	}
}
